<template>
	<view class="container">
		<!-- 地图容器 -->
		<view class="map-container">
			<!-- 使用WebView嵌入天地图H5页面 -->
			<web-view :src="mapUrl" @message="handleMessage"></web-view>
			
			<!-- 定位状态指示 -->
			<view class="location-status" v-if="!locationReady && mapLoaded">
				<text class="status-text">正在获取位置...</text>
			</view>
			<view class="location-error" v-if="locationErrorMsg">
				<text class="error-text">定位失败，请确保已开启位置权限</text>
			</view>
		</view>
		
		<!-- 定位按钮 -->
		<view class="location-btn" @tap="refreshLocation">
			<text class="iconfont">📍</text>
		</view>
		
		<!-- 底部可上拉列表 -->
		<uni-popup ref="popup" type="bottom" @change="handlePopupChange">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">附近公交线路</text>
					<view class="drag-bar"></view>
				</view>
				
				<!-- 位置信息显示 -->
				<view class="current-location" v-if="location.address">
					<text class="location-icon">📍</text>
					<text class="location-text">{{location.address}}</text>
				</view>
				
				<scroll-view scroll-y="true" class="bus-list" @scrolltolower="loadMoreRoutes">
					<view v-for="(route, index) in busRoutes" :key="index" class="bus-item" @tap="selectRoute(route)">
						<view class="bus-info">
							<text class="bus-number">{{route.number}}</text>
							<text class="bus-direction">{{route.direction}}</text>
						</view>
						<view class="bus-detail">
							<text class="bus-time">{{route.nextBusTime}}</text>
							<text class="bus-distance">{{route.distance}}</text>
						</view>
					</view>
					<view class="loading" v-if="loading">加载中...</view>
					<view class="empty-tip" v-if="busRoutes.length === 0 && !loading">
						<text>暂无公交线路信息</text>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { onMounted, ref } from 'vue'

export default {
	data() {
		return {
			mapUrl: '',
			location: {
				latitude: 39.9087,
				longitude: 116.3975
			},
			busRoutes: [],
			loading: false,
			popupVisible: false,
			locationReady: false,
			locationErrorMsg: '',
			mapLoaded: false,
			// 天地图API密钥
			tiandituKey: '5e76d73eede07b02568e9f72c5b08759'
		}
	},
	computed: {
		// 确保坐标有效
		validLatitude() {
			return this.location.latitude > 0 ? this.location.latitude : 39.9087
		},
		validLongitude() {
			return this.location.longitude > 0 ? this.location.longitude : 116.3975
		}
	},
	onLoad() {
		this.initLocation()
		
		// 延迟初始化地图
		setTimeout(() => {
			if (!this.locationReady) {
				// 初始化地图
				this.initMap()
			}
		}, 2000)
		
		// 自动显示底部列表
		this.$nextTick(() => {
			this.$refs.popup.open()
		})
	},
	methods: {
		async initLocation() {
			try {
				// 更精确的定位配置
				uni.showLoading({ title: '获取位置中...' })
				
				// 请求位置权限
				await this.checkLocationPermission()
				
				// 获取位置
				uni.getLocation({
					type: 'gcj02',
					geocode: true, // 获取地理编码信息
					highAccuracyExpireTime: 8000, // 高精度定位超时时间，增加超时时间
					isHighAccuracy: true, // 开启高精度定位
					success: (res) => {
						console.log('定位成功', res)
						// 验证坐标是否有效
						if (res.latitude > 0 && res.longitude > 0) {
							this.locationReady = true
							this.locationErrorMsg = ''
							this.location = {
								latitude: res.latitude,
								longitude: res.longitude,
								accuracy: res.accuracy || 0, 
								address: res.address || '',
								horizontalAccuracy: res.horizontalAccuracy || 0
							}
							
							// 更新地图URL
							this.initMap()
							this.loadNearbyBusRoutes()
						} else {
							this.handleLocationError('无效的位置坐标')
						}
					},
					fail: (err) => {
						this.handleLocationError(err)
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			} catch (e) {
				this.handleLocationError(e)
				uni.hideLoading()
			}
		},
		
		// 检查位置权限
		async checkLocationPermission() {
			return new Promise((resolve, reject) => {
				uni.authorize({
					scope: 'scope.userLocation',
					success: resolve,
					fail: () => {
						uni.showModal({
							title: '需要位置权限',
							content: '请授权位置权限以便获取附近公交信息',
							confirmText: '去设置',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting({
										success: (settingRes) => {
											if (settingRes.authSetting['scope.userLocation']) {
												resolve()
											} else {
												reject(new Error('用户拒绝位置权限'))
											}
										}
									})
								} else {
									reject(new Error('用户取消操作'))
								}
							}
						})
					}
				})
			})
		},
		
		// 处理定位错误
		handleLocationError(err) {
			console.error('定位失败', err)
			this.locationErrorMsg = typeof err === 'string' ? err : JSON.stringify(err)
			uni.showToast({
				title: '获取位置信息失败',
				icon: 'none'
			})
			// 失败时使用默认坐标初始化地图
			this.initMap()
		},
		
		// 初始化地图
		initMap() {
			// 构建更完整的天地图URL
			const params = {
				center: `${this.validLongitude},${this.validLatitude}`,
				level: '16', // 缩放级别
				tk: this.tiandituKey,
				showControls: 'true', // 显示控件
				showRuler: 'true', // 显示比例尺
				show3D: 'false', // 禁用3D
				showLabel: 'true', // 显示标签
				crs: 'EPSG3857' // 墨卡托投影
			}
			
			// 添加当前位置标记
			if (this.locationReady) {
				params.markers = `${this.validLongitude},${this.validLatitude}`;
				params.markerStyles = 'red'; // 红色标记
			}
			
			// 构建URL参数字符串
			const paramsStr = Object.entries(params)
				.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
				.join('&');
				
			// 完整的天地图分享页面URL
			this.mapUrl = `https://map.tianditu.gov.cn/share/index.html?${paramsStr}`;
			
			console.log('地图URL', this.mapUrl);
			this.mapLoaded = true;
		},
		
		// 刷新定位
		refreshLocation() {
			this.initLocation()
		},
		
		async loadNearbyBusRoutes() {
			this.loading = true
			try {
				// 获取附近公交站点
				await uni.request({
					url: 'https://api.tianditu.gov.cn/apiserver/around',
					data: {
						postStr: JSON.stringify({
							"keyWord": "公交站",
							"queryRadius": 1000,
							"queryType": 3,
							"needSubInfo": true,
							"needAll": false,
							"needPolygon": false,
							"needPre": false,
							"pageNum": 1,
							"pageSize": 10,
							"sourceSystem": 1,
							"sourceGuide": 1,
							"sideOpen": false,
							"center": `${this.validLongitude},${this.validLatitude}`
						}),
						type: 'query',
						tk: this.tiandituKey
					},
					success: (res) => {
						console.log('附近公交站点', res.data)
						// 处理返回结果
						if (res.data && res.data.pois) {
							this.handleBusStations(res.data.pois)
						} else {
							// 使用模拟数据
							this.useMockData()
						}
					},
					fail: () => {
						this.useMockData()
					}
				})
			} catch (e) {
				console.error('加载公交站点失败', e)
				this.useMockData()
			} finally {
				this.loading = false
			}
		},
		// 处理公交站点数据
		handleBusStations(stations) {
			if (!stations || stations.length === 0) {
				this.useMockData()
				return
			}
			
			// 生成公交线路数据
			this.busRoutes = stations.map(station => {
				const coords = station.lonlat.split(',')
				const distance = this.calculateDistance(
					this.validLatitude, 
					this.validLongitude,
					parseFloat(coords[1]),
					parseFloat(coords[0])
				)
				
				return {
					number: `${station.name.includes('路') ? station.name : station.name + '站'}`,
					direction: station.address || '未知方向',
					nextBusTime: this.getRandomTime(),
					distance: `${Math.round(distance)}米`,
					coords: station.lonlat
				}
			})
		},
		// 使用模拟数据
		useMockData() {
			this.busRoutes = [
				{
					number: '101路',
					direction: '火车站 → 汽车站',
					nextBusTime: '5分钟',
					distance: '300米'
				},
				{
					number: '201路',
					direction: '大学城 → 市中心',
					nextBusTime: '8分钟',
					distance: '500米'
				},
				{
					number: '301路',
					direction: '机场 → 火车站',
					nextBusTime: '12分钟',
					distance: '800米'
				}
			]
		},
		// 计算两点之间距离(米)
		calculateDistance(lat1, lon1, lat2, lon2) {
			const R = 6371000; // 地球半径(米)
			const dLat = this.deg2rad(lat2 - lat1)
			const dLon = this.deg2rad(lon2 - lon1)
			const a = 
				Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * 
				Math.sin(dLon/2) * Math.sin(dLon/2)
			const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
			return R * c
		},
		// 角度转弧度
		deg2rad(deg) {
			return deg * (Math.PI/180)
		},
		// 生成随机时间
		getRandomTime() {
			const minutes = Math.floor(Math.random() * 15) + 1
			return `${minutes}分钟`
		},
		// 处理WebView消息
		handleMessage(e) {
			console.log('WebView消息：', e)
		},
		loadMoreRoutes() {
			if (this.loading) return
			this.loadNearbyBusRoutes()
		},
		handlePopupChange(e) {
			this.popupVisible = e.show
		},
		selectRoute(route) {
			if (route.coords) {
				// 如果有坐标，更新地图显示该站点位置
				const coords = route.coords.split(',')
				const params = {
					center: route.coords,
					level: '17', // 放大一点查看站点详情
					tk: this.tiandituKey,
					markers: route.coords,
					markerStyles: 'blue' // 使用蓝色标记区分
				}
				
				// 构建URL参数字符串
				const paramsStr = Object.entries(params)
					.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
					.join('&');
				
				// 更新地图URL
				this.mapUrl = `https://map.tianditu.gov.cn/share/index.html?${paramsStr}`;
				
				// 关闭底部弹窗以便查看地图
				this.$refs.popup.close()
			} else {
				// 如果没有坐标，跳转到详情页
				uni.navigateTo({
					url: `/pages/booking/detail?number=${route.number}`
				})
			}
		}
	}
}
</script>

<style lang="scss">
.container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	position: relative;
	overflow: hidden; /* 防止内容溢出 */
}

.map-container {
	flex: 1;
	width: 100%;
	position: relative;
	z-index: 1; /* 确保地图层级正确 */
}

.location-status, .location-error {
	position: absolute;
	top: 20rpx;
	left: 0;
	right: 0;
	display: flex;
	justify-content: center;
	z-index: 10;
}

.status-text {
	background-color: rgba(0, 0, 0, 0.6);
	color: #fff;
	padding: 10rpx 30rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
}

.error-text {
	background-color: rgba(255, 59, 48, 0.9);
	color: #fff;
	padding: 10rpx 30rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
}

.current-location {
	background-color: #f8f8f8;
	padding: 20rpx;
	margin-bottom: 20rpx;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	
	.location-icon {
		margin-right: 10rpx;
		font-size: 28rpx;
	}
	
	.location-text {
		font-size: 24rpx;
		color: #666;
	}
}

.location-btn {
	position: absolute;
	right: 30rpx;
	bottom: 200rpx;
	width: 80rpx;
	height: 80rpx;
	background: #fff;
	border-radius: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	z-index: 5;
	
	.iconfont {
		font-size: 40rpx;
	}
}

.popup-content {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	padding: 30rpx;
	min-height: 60vh;
	z-index: 100; /* 确保弹出层在地图上方 */
}

.popup-header {
	padding-bottom: 20rpx;
	border-bottom: 1px solid #eee;
	
	.title {
		font-size: 32rpx;
		font-weight: bold;
		display: block;
		text-align: center;
	}
	
	.drag-bar {
		width: 60rpx;
		height: 6rpx;
		background: #ddd;
		border-radius: 3rpx;
		margin: 20rpx auto 0;
	}
}

.bus-list {
	height: calc(60vh - 150rpx);
}

.bus-item {
	padding: 20rpx 0;
	border-bottom: 1px solid #f5f5f5;
	display: flex;
	justify-content: space-between;
	align-items: center;
	
	&:active {
		background-color: #f5f5f5;
	}
}

.bus-info {
	.bus-number {
		font-size: 32rpx;
		font-weight: bold;
		margin-right: 20rpx;
	}
	
	.bus-direction {
		font-size: 28rpx;
		color: #666;
	}
}

.bus-detail {
	text-align: right;
	
	.bus-time {
		font-size: 28rpx;
		color: #3cc51f;
		margin-bottom: 10rpx;
		display: block;
	}
	
	.bus-distance {
		font-size: 24rpx;
		color: #999;
	}
}

.loading {
	text-align: center;
	padding: 20rpx;
	color: #999;
	font-size: 24rpx;
}

.empty-tip {
	text-align: center;
	padding: 50rpx 0;
	color: #999;
	font-size: 28rpx;
}
</style> 